<template>
  <div class="app-container">
    <h4 class="form-header h4">团队信息</h4>
    <el-form ref="form" :model="deptForm" label-width="80px" style="margin:10px 0">
      <el-row type="flex" justify="space-around">
        <el-col :span="7">
          <el-form-item label="团队名称" prop="deptName">
            <el-input v-model="deptForm.deptName" disabled style="width: 50%"/>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="负责人" prop="leader">
            <el-input  v-model="deptForm.leader" disabled style="width: 50%"/>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="联系电话" prop="phone">
            <el-input  v-model="deptForm.phone" disabled style="width: 50%"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h4 class="form-header h4">团队成员</h4>
    <el-form :model="queryParams" ref="queryForm"
             size="small" :inline="true"
             v-show="showSearch" label-width="68px"
             style="float: left;">
      <el-form-item label="医生姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入医生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>

    </el-form>
    <el-button
      type="primary"
      plain
      icon="el-icon-plus"
      size="mini"
      @click="handleAdd"
      style="float: right;"
    >添加医生</el-button>

        <el-table v-loading="loading" :data="userDeptList">
          <el-table-column label="医生编号" align="center" prop="userName" />
          <el-table-column label="医生姓名" align="center" prop="nickName" />
          <el-table-column label="担任角色" align="center" prop="senior">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.senior==1">组长</el-tag>
              <el-tag type="info" v-if="scope.row.senior==0">组员</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >角色调整</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
        <el-footer style="text-align: center">
          <el-button @click="close()">返回</el-button>
        </el-footer>

        <!-- 添加对话框 -->
        <el-dialog :title="title" :visible.sync="addOpen" width="50%" append-to-body height="60%">
          <div class="dialog-style">
            <el-table
              ref="addForm"
              :data="listDoctor.filter(data => !search || data.nickName.toLowerCase().includes(search.toLowerCase()))"
              @selection-change="handleDoctorSelection"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="医生编号" align="center" prop="userName" />
              <el-table-column label="医生姓名" align="center" prop="nickName" />
              <el-table-column align="right">
                <template slot="header">
                  <el-input
                    v-model="search"
                    size="mini"
                    placeholder="输入医生姓名搜索"/>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitAddForm">确 定</el-button>
            <el-button @click="addCancel">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 修改对话框 -->
        <el-dialog :title="title" :visible.sync="editOpen" width="500px" append-to-body>
          <el-form ref="editForm" :model="editForm" :rules="rules" label-width="80px">
            <el-form-item label="团队名" prop="deptName">
              <el-input v-model="editForm.deptName" readonly style="width: 70%"></el-input>
            </el-form-item>
            <el-form-item label="医生编号" prop="userName">
              <el-input v-model="editForm.userName" readonly style="width: 70%"></el-input>
            </el-form-item>
            <el-form-item label="医生姓名" prop="nickName">
              <el-input v-model="editForm.nickName" readonly style="width: 70%"></el-input>
            </el-form-item>
            <el-form-item label="担任角色" prop="senior">
              <el-radio v-model="editForm.senior" label="1">组长</el-radio>
              <el-radio v-model="editForm.senior" label="0">组员</el-radio>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitEditForm">确 定</el-button>
            <el-button @click="editCancel">取 消</el-button>
          </div>
        </el-dialog>
  </div>
</template>

<script>
import {
  listUserDept,
  delUserDept,
  addUserDept,
  updateUserDept, getDept, getUserByDept,
} from "@/api/system/dept";

export default {
  name: "distribution",
  data() {
    return {
      search:'',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      selectionsAdd:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医生分配表格数据
      userDeptList: [],
      listDoctor:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      addOpen:false,
      editOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        deptId: null,
        senior: null,
        common: null,
        userName:null,
        nickName:null,
        deptName:null
      },
      // 表单参数
      addForm:{},
      editForm: {},
      deptForm:{},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.queryParams.deptId=this.$route.params.id
    this.getDeptInfo();
    this.getList();
  },

  methods: {
    /** 查询医生分配列表 */
    getList() {
      this.loading = true;
      listUserDept(this.queryParams).then(response => {
        this.userDeptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取团队基本信息
    getDeptInfo(){
      getDept(this.queryParams.deptId).then(response=>{
        this.deptForm=response.data;
      })
    },

    addCancel(){
      this.addOpen = false;
      this.resetAdd();
    },
    // 取消按钮
    editCancel() {
      this.editOpen = false;
      this.resetEdit();
    },
    // 表单重置
    resetAdd() {
      this.addForm = {
        userId: null,
        deptId: null,
        senior: null,
        common: null,
        userName:null,
        nickName:null,
        deptName:null
      };
      this.resetForm("addForm");
    },
    resetEdit() {
      this.editForm = {
        userId: null,
        deptId: null,
        senior: null,
        common: null,
        userName:null,
        nickName:null,
        deptName:null
      };
      this.resetForm("editForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.userId)
    //   this.single = selection.length!==1
    //   this.multiple = !selection.length
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.addOpen = true;
      this.title = "添加医生";
      getUserByDept(this.queryParams.deptId).then(response=>{
        this.listDoctor = response.rows;
        this.addOpen=true;
      })
    },
    //多选医生
    handleDoctorSelection(selection){
      this.selectionsAdd = selection.map(item => item.userId);
    },
    /** 新增提交 */
    submitAddForm() {
      if(this.selectionsAdd.length<1){
        this.$message.warning('请至少选择一位医生！');
        return
      }else {
        let udList=[];
        this.selectionsAdd.forEach(item => {
            udList.push({deptId:this.queryParams.deptId,userId:item,senior:'0'});
        });
        addUserDept(udList).then(response=>{
          this.$modal.msgSuccess("新增成功");
          this.addOpen = false;
          this.getList();
        })
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetEdit();
      //是组员
      if(row.senior=='0'){
        listUserDept({userId:row.userId,senior:'1'}).then(response=>{
          //在其他团队中有担任组长
          if(response.rows.length>0){
            this.$message.warning('该医生已在其他团队中担任组长，暂不可调整为组长！')
          }else {
            this.dialogOpen(row)
          }
        })
      }else {
        this.dialogOpen(row)
      }
    },
    dialogOpen(row){
      listUserDept({deptId:row.deptId,userId:row.userId}).then(response => {
        this.editForm = response.rows[0];
        this.editOpen = true;
        this.title = "修改医生分配";
      });
    },

    submitEditForm(){
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          if (this.editForm.userId && this.editForm.deptId) {
            updateUserDept(this.editForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.editOpen = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认将医生"' + row.userName + '"从"' + row.deptName + '"中移除？').then(function() {
        return delUserDept({userId:row.userId,deptId:row.deptId,senior:row.senior});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('system/userDept/export', {
    //     ...this.queryParams
    //   }, `userDept_${new Date().getTime()}.xlsx`)
    // },
    close() {
      const obj = { path: "/dept" };
      this.$tab.closeOpenPage(obj);
    },
  }
};
</script>

<style scoped>

.dialog-style{
  height: 60vh;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>


